package com.manage.project.service.impl;

import cn.hutool.core.lang.UUID;
import com.manage.common.entity.FileInfo;
import com.manage.common.exception.HxException;
import com.manage.project.service.UpYunService;
import com.manage.utils.StringTool;
import com.upyun.RestManager;
import com.upyun.UpYunUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UpYunServiceImpl implements UpYunService {

    public String address = "http://hongma-resource.test.upcdn.net";

    @Resource
    private RestManager manager;


    public static String getFileSuffix(@NotNull(message = "找不到文件名") String fileName) {
        Integer index = fileName.lastIndexOf(".");
        if (index < 0) {
            throw new HxException("文件名错误!");
        }
        return fileName.substring(index);
    }

    public static String createNewFileNameByFileName(@NotNull(message = "找不到文件名") String fileName) {
        String newFilename = UUID.randomUUID().toString().replaceAll("-", "") + getFileSuffix(fileName);
        return newFilename;
    }

    public static String createNewFileNameBySuffix(@NotNull(message = "找不到文件名") String suffix) {
        int index = suffix.indexOf(".");
        if (index != 0) {
            throw new HxException("后缀必须由 . 开头！");
        }
        String newFilename = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        return newFilename;
    }

    @Override
    public String coverUploadMultipartFile(MultipartFile file, String filePath) {
        StringTool.checkIfStartsWithSlash(filePath);
        // 获取新的图片名
        String filename = file.getOriginalFilename();
        String newFilename = createNewFileNameByFileName(getFileSuffix(filename));
        // 初始化
        Map<String, String> params = new HashMap<>();
        // GMT格式时间
        params.put("Date", UpYunUtils.getGMTDate());
        params.put("Content-Length", file.getSize() + "");
        try {
            StringBuilder sb = new StringBuilder();
            if (StringUtils.isNotBlank(filePath)) {
                sb.append(filePath);
            }
            sb.append("/");
            sb.append(newFilename);
            // 上传图片
            Response result = manager.writeFile(sb.toString(), file.getBytes(), params);
            if (result.isSuccessful()) {
                // 访问链接
                String url = address + sb.toString();
                return url;
            } else {
                // 上传失败
                throw new HxException("上传失败！错误编码：" + result.code());
            }
        } catch (Exception e) {
            throw new HxException(e.toString());
        }
    }

    @Override
    public String uploadMultipartFile(MultipartFile file, String filePath) {
        StringTool.checkIfStartsWithSlash(filePath);
        // 获取新的图片名
        String filename = file.getOriginalFilename();
        String newFilename = createNewFileNameByFileName(getFileSuffix(filename));
        // 初始化
        Map<String, String> params = new HashMap<>();
        // GMT格式时间
        params.put("Date", UpYunUtils.getGMTDate());
        params.put("Content-Length", file.getSize() + "");
        try {
            StringBuilder sb = new StringBuilder();
            if (StringUtils.isNotBlank(filePath)) {
                sb.append(filePath);
            }
            sb.append("/");
            sb.append(newFilename);
            // 上传图片
            String name = sb.toString();
            if (getFileInfo(name) != null) {
                throw new HxException("文件名重复请重试！");
            }
            Response result = manager.writeFile(name, file.getBytes(), params);
            if (result.isSuccessful()) {
                // 访问链接
                String url = address + "/" + name;
                return url;
            } else {
                // 上传失败
                throw new HxException("错误编码：" + result.code());
            }
        } catch (Exception e) {
            throw new HxException(e.toString());
        }
    }

    @Override
    public String uploadDataFile(String suffix, byte[] data) {
        String fileName = createNewFileNameBySuffix(suffix);
        // 初始化
        Map<String, String> params = new HashMap<>();
        // GMT格式时间
        params.put("Date", UpYunUtils.getGMTDate());
        params.put("Content-Length", data.length + "");
        // 文件名
        try {
            Response result = manager.writeFile(fileName, data, params);
            if (result.isSuccessful()) {
                // 访问链接
                String url = address + "/" + fileName;
                return url;
            } else {
                // 上传失败
                throw new HxException("错误编码：" + result.code());
            }
        } catch (Exception e) {
            throw new HxException(e.toString());
        }


    }

    @Override
    public Boolean createDir(String filePath) {
        try {
            StringTool.checkIfStartsWithSlash(filePath);
            Response result = manager.mkDir(filePath);
            if (result.isSuccessful()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new HxException(e.getMessage());
        }
    }

    @Override
    public Boolean deleteDir(String filePath) {
        try {
            StringTool.checkIfStartsWithSlash(filePath);
//            String file_to_path = StringTool.addPrefixWithBuilder(filePath, "/"+bucketName);
            Response result = manager.rmDir(filePath);
            if (result.isSuccessful()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new HxException(e.getMessage());
        }
    }

    @Override
    public String readDirIter(String path) {
        try {
            StringTool.checkIfStartsWithSlash(path);
            Response result = manager.readDirIter(path, null);
            if (result.isSuccessful()) {
                return result.body().string();
            } else {
                throw new HxException("错误编码：" + result.code());
            }
        } catch (Exception e) {
            throw new HxException(e.getMessage());
        }
    }

    @Override
    public FileInfo getFileInfo(String filePath) {
        try {
            Response result = manager.getFileInfo(filePath);
            if (result.isSuccessful()) {
                String type = result.headers().get("x-upyun-file-type");
                String size = result.headers().get("x-upyun-file-size");
                String date = result.headers().get("x-upyun-file-date");
                String md5 = result.headers().get("Content-Md5");
                return new FileInfo(type, size, date, md5);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @SneakyThrows
    @Override
    public String downloadFile(String path) {
        Response response = manager.readFile(path);
        if (response.isSuccessful()) {
            return response.body().toString();
        }
        return "请求失败";
    }

    @Override
    public Boolean deleteFile(String filePath) {
        try {
            Response result = manager.deleteFile(filePath, null);
            if (result.isSuccessful()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public String getBucketUsage() {
        try {
            Response result = manager.getBucketUsage();
            if (result.isSuccessful()) {
                System.out.println(result.message());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Boolean movefile(String path, String resourcePath, String bucketName) {
        try {
            StringTool.checkIfStartsWithSlash(path);
            StringTool.checkIfStartsWithSlash(resourcePath);
            Map<String, String> params = new HashMap<>();
            String resource_to_path = StringTool.addPrefixWithBuilder(resourcePath, "/" + bucketName);
            params.put("X-Upyun-Move-Source", resource_to_path);
            params.put("Content-Length", "0");
            Response result = manager.moveFile(path, resource_to_path, params);
            if (result.isSuccessful()) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new HxException(e.getMessage());
        }
        return false;
    }

    @Override
    public Boolean copyfile(String path, String resourcePath, String bucketName) {
        try {
            StringTool.checkIfStartsWithSlash(path);
            StringTool.checkIfStartsWithSlash(resourcePath);
            Map<String, String> params = new HashMap<>();
            String resource_to_path = StringTool.addPrefixWithBuilder(resourcePath, "/" + bucketName);
            params.put("X-Upyun-Copy-Source", resource_to_path);
            params.put("Content-Length", "0");
            Response result = manager.moveFile(path, resource_to_path, params);
            if (result.isSuccessful()) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new HxException(e.getMessage());
        }
        return false;
    }


}
